﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AlbumDesign
{
    public class Navigator<T> : INotifyPropertyChanged
    {
        public Navigator(ObservableCollection<T> Pages)
        {
            collection = Pages;
            ToFirst();
        }

        ObservableCollection<T> collection;

        #region Notification

        public event PropertyChangedEventHandler PropertyChanged;

        private void RaisePropertyChangedEvent(string PropertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
        }

        private void NotifyCurrentChanged()
        {
            RaisePropertyChangedEvent("CurrentPage");
            RaisePropertyChangedEvent("CurrentPageNo");
        }

        #endregion

        public T CurrentPage { get; set; }
        /// <summary>
        /// 0-based
        /// </summary>
        public int CurrentPageNo
        {
            get
            {
                return collection.IndexOf(CurrentPage);
            }
        }

        public void ToFirst()
        {
            CurrentPage = collection.First();
            NotifyCurrentChanged();
        }

        public void ToLast()
        {
            CurrentPage = collection.Last();
            NotifyCurrentChanged();
        }

        public bool ToPrev()
        {
            int i = CurrentPageNo;
            if (i <= 0)
            {
                return false;
            }
            else
            {
                CurrentPage = collection.ElementAt(i - 1);
                NotifyCurrentChanged();
                return true;
            }
        }
        
        public bool ToNext()
        {
            int i = CurrentPageNo;
            if (i == (collection.Count - 1))
            {
                return false;
            }
            else
            {
                CurrentPage = collection.ElementAt(i + 1);
                NotifyCurrentChanged();
                return true;
            }
        }

        public bool To(int PageNo)
        {
            if (PageNo < collection.Count)
            {
                CurrentPage = collection.ElementAt(PageNo);
                NotifyCurrentChanged();
                return true;
            }
            else return false;
        }

    }
}
